import org.molamil.acto.commands.Command;
import org.molamil.acto.commands.CommandContext;
import org.molamil.acto.commands.CommandMaster;
import org.molamil.acto.commands.CommandRequest;
import org.molamil.acto.commands.CommandsConf;
import org.molamil.acto.commands.InvalidCmdError;
import org.molamil.acto.core.Logger;
import org.molamil.commons.StringUtil;

/**
 * @author Jorge Hernandez
 */
class org.molamil.acto.commands.CommandBuilder {
	
	
	// Constants
	
	public static var ERROR_INVALID_CMD_CLASS:String = "ERROR: The Cmd class could not be loaded: \"{className}\".";
	
	
	// Properties
	
	private static var log:Logger = Logger.getLogger("CommandBuilder");
	
	
	// Functions
	
	public static function create(context:CommandContext, request:CommandRequest):CommandMaster {
		log.info("create() name = " + context.name);
		var master:CommandMaster = new CommandMaster();
		master.context = context;		master.request = request;		master.cmd = buildCmd(context);
		return master;
	}
	
	private static function buildCmd(context:CommandContext):Command {
		var className:String = context.className;
		log.debug("buildCmd() className = " + className);
		if (className.indexOf(".") == -1)
			className = CommandsConf.defaultCmdPackage + "." + className;
		var f:Function = eval("" + className);
		if (f == null) {
			log.severe("Invalid cmd class");
			var msg:String = StringUtil.replace(ERROR_INVALID_CMD_CLASS, "{className}", className);
			throw new InvalidCmdError(msg);
		}
		return new f(context);
	}
	
	
}
